<?php

class ProjectsController extends Controller
{
	public function delTree($folder) { 

		$files = glob( $folder . DIRECTORY_SEPARATOR . '*');
		foreach( $files as $file ){
			if($file == '.' || $file == '..'){continue;}
			if(is_dir($file)){
				$this->delTree( $file );
			}else{
				@unlink( $file );
			}
		}
		@rmdir( $folder ); 
	} 
	public function actionSearch(){
		$q = Yii::app()->request->getParam('q',null);
		
		$projects = Projects::model()->searchProjects($q);
		
		if(!empty($projects)){
			jsonOut(array(
				'error'=>false,
				'data'=>$projects,
			));
			
		}else{
			jsonOut(array(
				'error'=>true,
				
			));
		}
	}
	public function actionRemove(){
		$id = Yii::app()->request->getParam('id',null);
		if(Yii::app()->user->isGuest){
			jsonOut(array(
				'error'=>true,
				'message'=>'Pls login'
			));
		}
		$project = Projects::model()->findByPk(outBin($id));
		
		
		$structure = "";
		if(!empty($project)){
			$structure = 'projects/'.outStr(currentUser(true)->id)."/".$project->name;
			$this->delTree($structure);
			
			$project->delete();
			
			$structure = 'projects/source/'.outStr(currentUser(true)->id)."/".$project->name;
			$this->delTree($structure);
		}
		
		jsonOut(array(
			'error'=>false,
			'structure'=>$structure
		));
		
	}
	public function actionSave(){
		if(Yii::app()->user->isGuest){
			jsonOut(array(
				'error'=>true,
				'message'=>'Pls login'
			));
		}
		if(empty($_POST)){
			jsonOut(array(
				'error'=>true,
				'message'=>'Form params not found'
			));
		}
		$name = trim($_POST['name']);
		$project = Projects::model()->findAllByAttributes(array(
			'owner_id'=>currentUser(true)->id,
			'name'=>$name
		));
		if(!empty($project)){
			jsonOut(array(
				'error'=>true,
				'message'=>'Cannot create a project when that file already exists'
			));
		}
		$model = new Projects;
		$model->created = time();
		$model->name = $name;
		$model->owner_id = currentUser(true)->id;
		if($model->save()){
			
			$model->owner_id = outStr($model->owner_id);
			$model->id = outStr($model->id);
			
			$model->createTree();
			
			$dir = "projects/".outStr(currentUser(true)->id) ."/".$model->name;
			$f = FileTree::php_file_tree($dir,"",array(),$model->name,outStr($model->id));
			$data = $model->attributes;
			$data['dir'] = $f;
			jsonOut(array(
				'error'=>false,
				'data'=>$data,
				'dir'=>$f,
				'message'=>'The project  has been saved'
			));
		}else{
			jsonOut(array(
				'error'=>true,
				'message'=>$model->getErrors()
			));
		}
	}
	public function actionGet(){
		$projects = Projects::model()->findAllByAttributes(array(
			'owner_id'=>Yii::app()->user->id
		));

		$data = array();
		if(!empty($projects)){
			foreach($projects as $key=>$project){
				$project->id = outStr($project->id);
				$data[] = $project->attributes;
			}
		}
		
		
		jsonOut(array(
			'error'=>false,
			'data'=>$data,
		));
	}
	
}